package com.example.front.serivce;

import com.alibaba.fastjson.JSONArray;
import com.example.common.dto.ListDto;
import com.example.common.dto.Pagination;
import com.example.common.exception.BusinessException;
import com.example.front.dto.*;
import com.example.front.entity.*;
import com.example.front.mapper.EquipmentMapper;
import com.example.front.mapper.MaintenanceMapper;
import com.example.front.mapper.MaintenanceUserMapper;
import com.example.interceptor.UserContext;
import com.example.passport.entity.User;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import javax.validation.Valid;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

@Service
public class MaintenanceService {

    @Resource
    MaintenanceMapper maintenanceMapper;
    @Resource
    MaintenanceUserService maintenanceUserService;
    @Resource
    CategoryService categoryService;
    @Resource
    LineService lineService;
//    /**
//     * 创建设备
//     */
//    public void createEquipment(Equipment equipment) {
//        User me = UserContext.getUser();
//        equipmentMapper.create(equipment);
//    }

    /**
     * 列出设备
     */
    public ListDto<Maintenance> list(Maintenance condition, Pagination pagination) {
        User user = UserContext.getUser();
        condition.setTenantId(user.getTenantId());
        long total = maintenanceMapper.count(condition);
        if (total == 0) {
            return new ListDto<>(new ArrayList<>(), pagination);
        }
        pagination.setTotal(total);
        List<Maintenance> maintenanceList = maintenanceMapper.findAll(condition, pagination);

        //不为空获取产线按钮盒信息
        if (maintenanceList != null && maintenanceList.size() > 0) {
            for (Maintenance maintenance : maintenanceList) {
                if (maintenance.getCategoryId() != 0) {
                    Category category = categoryService.findbyId(maintenance.getCategoryId());
                    if (category != null) {
                        maintenance.setCategoryName(category.getName());
                    }
                }
                String strLineId = maintenance.getLineId();
                if (strLineId != null && !"".equals(strLineId)) {
                    ArrayList<String> lineName = new ArrayList<>();

                    List<String> lineIdList = Arrays.asList(strLineId.split(","));

                    for (String s : lineIdList) {
                        Line line = lineService.findById(Long.valueOf(s));
                        if (line != null) {
                            lineName.add(line.getName());
                        }
                    }
                    maintenance.setLineName(lineName);
                }

            }
        }

        return new ListDto(maintenanceList, pagination);
    }

    /**
     * 跟新数据
     */
    @Transactional
    public void update(@Valid MaintenanceDto maintenanceDto) {
        User user = UserContext.getUser();
        maintenanceDto.setTenantId(user.getTenantId());
        //删除
        maintenanceUserService.delete(maintenanceDto.getId());
        createMaintenanceEventUser(maintenanceDto);

        //修改
        List<String> lineIdList = maintenanceDto.getLineIdList();
        if (lineIdList != null && lineIdList.size() > 0){
            String join = String.join(",", lineIdList) + ",";
            maintenanceDto.setLineId(join);
            if (maintenanceMapper.update(maintenanceDto) == 0) {
                throw new BusinessException("修改失败");
            }
        }else{
            throw new BusinessException("请选择产线");
        }


    }

    /**
     * 删除
     */
    public void deletion(long id) {
        User user = UserContext.getUser();
        if (maintenanceMapper.deletion(id, user.getTenantId()) < 0) {
            throw new BusinessException("操作失败");
        }
    }

    /**
     * 查询单个
     */
    public Maintenance findById(Long id) {
        Maintenance maintenance = maintenanceMapper.findById(id);
        if (maintenance != null) {
            String lineId = maintenance.getLineId();
            if (lineId != null && !"".equals(lineId)){
                List<String> strings = Arrays.asList(lineId.split(","));
                List<Long> longs = strings.stream().map(Long::parseLong).collect(Collectors.toList());
                maintenance.setLineIdList(longs);
            }

            maintenance.setTenantId(UserContext.getUser().getTenantId());
            List<BoxEventUserDto> boxEventUserDtoList = maintenanceUserService.findAll(maintenance);
            maintenance.setEvent(boxEventUserDtoList);
        }
        return maintenance;
    }

    /**
     * 新增班组
     */
    @Transactional
    public void create(@Valid MaintenanceDto maintenanceDto) {
        User user = UserContext.getUser();
        maintenanceDto.setTenantId(user.getTenantId());
        maintenanceMapper.create(maintenanceDto);
        createMaintenanceEventUser(maintenanceDto);
    }

    /**
     * 创建用户和事件的关系
     */
    @Transactional
    public void createMaintenanceEventUser(@Valid MaintenanceDto maintenanceDto) {
        User user = UserContext.getUser();
        List<BoxEventUserCreateDto> eventList =
                JSONArray.parseArray(maintenanceDto.getEvent(), BoxEventUserCreateDto.class);
        for (BoxEventUserCreateDto dto : eventList) {
            List<Long> userIdList = dto.getUserId();
            if (userIdList == null || userIdList.size() < 0) continue;

            MaintenanceUser maintenanceUser = new MaintenanceUser();
            for (Long aLong : userIdList) {
                maintenanceUser.setMId(maintenanceDto.getId());
                maintenanceUser.setUserId(aLong);
                maintenanceUser.setEventId(dto.getEventId());
                if (dto.getLevelId() == null) {
                    maintenanceUser.setLevelId(1L);
                } else {
                    maintenanceUser.setLevelId(dto.getLevelId());
                }
                maintenanceUser.setTenantId(user.getTenantId());
                maintenanceUserService.create(maintenanceUser);
            }

        }
    }

    /**
     * 删除
     */
    public Maintenance selectOne(Maintenance maintenance) {
        return maintenanceMapper.selectOne(maintenance);
    }

}
